package demo01;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

@AllArgsConstructor
@NoArgsConstructor
@Data
class Student {
    private Integer id;
    private String name;
    private Integer age;

    @Override
    public String toString() {
        return id + "-" + name + "-" + age;
    }
}


public class Test01 {
    public static void main(String[] args) throws IOException {
        List<Student> studentList = new ArrayList<>();
        studentList.add(new Student(1, "五维", 18));
        studentList.add(new Student(2, "六维", 19));
        studentList.add(new Student(3, "七维", 20));
        saveStudent(studentList);
        List<Student> students = loadStudents();
        System.out.println(students);
    }

    private static void saveStudent(List<Student> studentList) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("student.txt"));
        for (Student student : studentList) {
            bufferedWriter.write(student.toString());
            bufferedWriter.newLine();
            bufferedWriter.flush();
        }
    }

    private static List<Student> loadStudents() throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new FileReader("student.txt"));
        List<Student> studentList = new ArrayList<>();

        String line;
        while ((line = bufferedReader.readLine()) != null) {
            String[] studentInfoArray = line.split("-");
            studentList.add(new Student(Integer.parseInt(studentInfoArray[0]), studentInfoArray[1], Integer.parseInt(studentInfoArray[2])));
        }
        return studentList;
    }


}
